/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Views;

import Common.ChagesLanguage;
import Common.CheckForm;
import Common.ConnectionDB;
import Common.Constant;
import DAO.SuppliersDAO;
import Helper.SuppliersHepler;
import Model.SuppliersModel;
import java.awt.Toolkit;
import java.io.File;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author KIENLT
 */
public class Suppliers extends javax.swing.JDialog {

    ArrayList<SuppliersHepler> arrSupplier;
    ArrayList<SuppliersHepler> arrSupplierList;
    SuppliersHepler supplierData;
    ResultSet rs = null;
    private ResourceBundle rb;

    /**
     * Creates new form Suppliers
     */
    public Suppliers(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        loadLanguage();
        loadSuppliers();
        this.setLocationRelativeTo(null);
        try {
            setIconImage(Toolkit.getDefaultToolkit().getImage(new File("src\\Images\\Icon-Form.png").getCanonicalPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadLanguage() {
        ChagesLanguage.readFileLanguage();
        Locale locale = new Locale(ChagesLanguage.languageCode, ChagesLanguage.countryCode);
        rb = ResourceBundle.getBundle(ChagesLanguage.urlLanguage, locale);
        lblId.setText(rb.getString("Id"));
        lblName.setText(rb.getString("Sname"));
        lblDescription.setText(rb.getString("Description"));
        btnAdd.setText(rb.getString("Add"));
        btnUpdate.setText(rb.getString("Update"));
        btnDelete.setText(rb.getString("Delete"));
        this.setTitle(rb.getString("Suppliers"));
    }

    private void loadSuppliers() {
        try {
            arrSupplier = SuppliersDAO.FindAll(ConnectionDB.ConnectionDatabase());
            arrSupplierList = new ArrayList<SuppliersHepler>();

            for (SuppliersHepler item : arrSupplier) {
                arrSupplierList.add(item);
            }

            tblSuppliers.setModel(new SuppliersModel(arrSupplierList));

            DefaultTableColumnModel model = (DefaultTableColumnModel) tblSuppliers.getColumnModel();
            TableColumn tblCol = model.getColumn(0);
            tblCol.setPreferredWidth(10);
        } catch (Exception ex) {
            try {
                ConnectionDB.CloseDB(ConnectionDB.ConnectionDatabase());
            } catch (Exception ex1) {
                Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex1);
            }
            ex.printStackTrace();
        }
//        if (arrUserList.size() > 0) {
//            tblUsers.getSelectionModel().setSelectionInterval(0, 0);
//            fillOneDepartment();
//        }

        tblSuppliers.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {

                    @Override
                    public void valueChanged(ListSelectionEvent e) {

                        boolean adjust = e.getValueIsAdjusting();
                        if (adjust) {
                            FindOne();
                        }
                    }
                });
    }

    private void FindOne() {
        try {
            supplierData = new SuppliersHepler();
            int row = tblSuppliers.getSelectedRow();
            supplierData.setId(tblSuppliers.getValueAt(row, 0).toString());
            rs = SuppliersDAO.FindOne(ConnectionDB.ConnectionDatabase(), supplierData);
            if (rs.next()) {
                txtId.setText(rs.getString("SID"));
                txtName.setText(rs.getString("SName"));
                txtDescription.setText(rs.getString("Description"));
            }
        } catch (Exception ex) {
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblSuppliers = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        lblId = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        lblName = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        lblDescription = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtDescription = new javax.swing.JTextArea();
        btnAdd = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Suppliers");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        tblSuppliers.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tblSuppliers);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        lblId.setText("jLabel1");

        txtId.setEditable(false);

        lblName.setText("Suppliers Name");

        lblDescription.setText("Desctiption");

        txtDescription.setColumns(20);
        txtDescription.setRows(5);
        jScrollPane2.setViewportView(txtDescription);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon-add.png"))); // NOI18N
        btnAdd.setText("jButton1");
        btnAdd.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnAdd.setPreferredSize(new java.awt.Dimension(100, 30));
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon-update.png"))); // NOI18N
        btnUpdate.setText("jButton1");
        btnUpdate.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnUpdate.setPreferredSize(new java.awt.Dimension(100, 30));
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon-delete.png"))); // NOI18N
        btnDelete.setText("jButton1");
        btnDelete.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnDelete.setPreferredSize(new java.awt.Dimension(100, 30));
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblId)
                            .addComponent(lblDescription))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(37, 37, 37)
                                .addComponent(lblName)
                                .addGap(26, 26, 26)
                                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane2)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(152, 152, 152)
                        .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblId)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblName)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDescription)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            if (checkForm()) {
                SuppliersHepler supplier = new SuppliersHepler();
                supplier.setName(txtName.getText());
                supplier.setDescription(txtDescription.getText());
                int query = SuppliersDAO.Insert(ConnectionDB.ConnectionDatabase(), supplier);
                if (query > 0) {
                    JOptionPane.showMessageDialog(this, rb.getString("InsertSuccess") + ".", rb.getString("Message"), JOptionPane.INFORMATION_MESSAGE);
                    loadSuppliers();
                } else {
                    JOptionPane.showMessageDialog(this, rb.getString("InsertError"), rb.getString("Error"), JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            if (checkForm()) {
                SuppliersHepler supplier = new SuppliersHepler();
                supplier.setId(txtId.getText());
                supplier.setName(txtName.getText());
                supplier.setDescription(txtDescription.getText());
                int query = SuppliersDAO.Update(ConnectionDB.ConnectionDatabase(), supplier);
                if (query > 0) {
                    JOptionPane.showMessageDialog(this, rb.getString("UpdateSuccess") + ".", rb.getString("Message"), JOptionPane.INFORMATION_MESSAGE);
                    loadSuppliers();
                } else {
                    JOptionPane.showMessageDialog(this, rb.getString("UpdateError"), rb.getString("Error"), JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_btnUpdateActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        try {
            supplierData = new SuppliersHepler();
            supplierData.setId(txtId.getText());
            int option = JOptionPane.showConfirmDialog(this, rb.getString("Youaresuredelete") + "?", rb.getString("Message"), JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {
                int query = SuppliersDAO.Delete(ConnectionDB.ConnectionDatabase(), supplierData);
                if (query > 0) {
                    JOptionPane.showMessageDialog(this, rb.getString("DeleteSuccess") + ".", rb.getString("Message"), JOptionPane.INFORMATION_MESSAGE);
                    loadSuppliers();
                } else {
                    JOptionPane.showMessageDialog(this, rb.getString("DeleteError") + ".", rb.getString("Error"), JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private boolean checkForm() {
        if (txtName.getText().equals("")) {
            JOptionPane.showMessageDialog(this, rb.getString("SupplierNameisnotempty") + ".", rb.getString("Warning"), JOptionPane.WARNING_MESSAGE);
            txtName.requestFocus();
            return false;
        }
        return true;
    }
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /*
//         * Set the Nimbus look and feel
//         */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /*
//         * If Nimbus (introduced in Java SE 6) is not available, stay with the
//         * default look and feel. For details see
//         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(Suppliers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(Suppliers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(Suppliers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(Suppliers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /*
//         * Create and display the dialog
//         */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                Suppliers dialog = new Suppliers(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//
//                    @Override
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblDescription;
    private javax.swing.JLabel lblId;
    private javax.swing.JLabel lblName;
    private javax.swing.JTable tblSuppliers;
    private javax.swing.JTextArea txtDescription;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtName;
    // End of variables declaration//GEN-END:variables
}
